# -*- coding: utf-8 -*-
# @Time    : 2024/4/16 19:07
# @Author  : Alvin
# @File    : CheUtil.py
# @Des     :
import random
import re
import time
from datetime import datetime

# 获取cookie
from constants import Constants


def get_request_header(token, requestToken):
    header = {
        "accept": "*/*",
        "accept-language": "zh-CN,zh;q=0.9",
        "cache-control": "no-cache",
        "content-type": "application/json; charset=UTF-8",
        "hango-origin": "lanqiao",
        "lqgraytmscode": "78210",
        "lqgrayversion": "1.5.9",
        "origin": "https://t9bs.lqfast.com",
        "pragma": "no-cache",
        "priority": "u=1, i",
        "referer": "https://t9bs.lqfast.com/",
        "requesttoken": requestToken,
        "sec-ch-ua": "\"Google Chrome\";v=\"137\", \"Chromium\";v=\"137\", \"Not/A)Brand\";v=\"24\"",
        "sec-ch-ua-mobile": "?0",
        "sec-ch-ua-platform": "\"Windows\"",
        "sec-fetch-dest": "empty",
        "sec-fetch-mode": "cors",
        "sec-fetch-site": "same-site",
        "tenantcode": "78210",
        "token": token,
        "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/137.0.0.0 Safari/537.36"
    }
    return header


def get_app_header():
    return {
        "Connection": "close",
        "content-type": "application/x-www-form-urlencoded",
        "User-Agent": "okhttp/3.4.1",
        "Host": "app.lqfast.com",
        "Accept-Encoding": "gzip"
    }


def get_param_u(token):
    """
    获取参数中的u，用户信息，固定值
    :param token:
    :return:
    """
    u = {
        "token": token,
        "tmsCode": "78210",
        "userId": "优斯雅通达",
        "userName": "优斯雅通达",
        "loginSite": "优斯雅通达",
        "tmsbshxsite": "优斯雅通达",
        "browserId": None,
        "loginSiteCode": "20",
        "tmsbsgsname": "佛山市晋良物流有限公司"
    }
    return u


def generate_random_digits(length):
    """
    随机生成指定长度的字符串
    :param length:
    :return:
    """
    random_digits = ''.join(random.choices('0123456789', k=length))
    return random_digits


# 获取物流描述
def getLogisticsDescriptionByLogisticsItem(dbItem, updateType, context):
    """
    根据快递获取物流描述
    :param dbItem:
    :param updateType:
    :param context:
    :return:
    """
    des = context
    phone_numbers = re.findall(r'1\d{10}', context)
    pickingCode: str = dbItem.get("pickingCode", None)
    mobile = Constants.default_tel
    if phone_numbers is not None and len(phone_numbers) > 0:
        mobile = phone_numbers[0]
    express = dbItem.get("express", None)
    if express is not None:
        if "快递" in express:
            express = express.replace("快递", "")
        if "速递" in express:
            express = express.replace("速递", "")
    mailNo = dbItem.get("mailNo", None)
    if updateType == "送货中":
        des = context
    elif updateType == '已送货':
        if not pickingCode:
            if not express or express == 'undefined':
                des = context
            else:
                des = f"待取件，【取件请报{express}单号后5位:{mailNo[-5:]}】,{context}"
        else:
            if pickingCode.startswith("取件请出示"):
                if not express or express == 'undefined':
                    des = f"待取件，取件码:{pickingCode},{context}"
                else:
                    des = f"待取件，【取件请报{express}单号后5位:{mailNo[-5:]}】,{context}"
            else:
                if "取件请报" in pickingCode:
                    if not express or express == 'undefined':
                        des = f"待取件，【取件请报{express}单号后5位:{mailNo[-5:]}】,{context}"
                    else:
                        des = f"待取件，{pickingCode},{context}"
                else:
                    des = f"待取件，{express}取件码:{pickingCode},{context}"
    elif updateType == '已签收':
        des = f"您的包裹已签收，如有疑问请联系:{mobile},期待再次为您服务！"
    if len(des) > 100:
        des = des[:99]
    return des


def get_update_pre_param(order_detail):
    param = [
        {
            "shipper": order_detail.get("shipper"),
            "backremark": order_detail.get("backremark"),
            "acczz": order_detail.get("acczz"),
            "accdeclare": order_detail.get("accdeclare"),
            "tosite": order_detail.get("tosite"),
            "consigneetel": order_detail.get("consigneetel"),
            "willbesenddate": order_detail.get("willbesenddate"),
            "volumn": order_detail.get("volumn"),
            "backcustomer": order_detail.get("backcustomer"),
            "accnow": 0,
            "outmadeby": order_detail.get("outmadeby"),
            "middlesite": "",
            "factsenddate": "",
            "pageMaxID": 148421,
            "state": 10,
            "outtraceisover": 0,
            "accyaokanozz": "",
            "bankcode": "",
            "backqty": "",
            "consignee": order_detail.get("consignee"),
            "accback": 0,
            "cmbcservicetype": "",
            "pageDataTotal": 2,
            "shippermb": "1762328234",
            "weight": 0,
            "shippercompany": "",
            "keyid": "",
            "vipno": "",
            "outaccback": 0,
            "fetchdate": order_detail.get("fetchdate"),
            "unit": order_detail.get("unit"),
            "cmbcstate": order_detail.get("cmbcstate"),
            "pageMinID": 148420,
            "bsite": order_detail.get("bsite"),
            "consigneemb": order_detail.get("consigneemb"),
            "qty": order_detail.get("qty"),
            "accdaishou": order_detail.get("accdaishou"),
            "billdate": order_detail.get("billdate"),
            "outcygs": order_detail.get("outcygs"),
            "mb2": "999183503267037708",
            "billno": order_detail.get("billno"),
            "fetchman": "",
            "backdatebsite": order_detail.get("backdatebsite"),
            "okprocess": order_detail.get("okprocess"),
            "ischecked": 0,
            "remark": "",
            "outbillno": "",
            "yewuyuan": "",
            "outtracehistry": "",
            "accarrived": 0,
            "outacctype": "",
            "createby": order_detail.get("createby"),
            "arrivedconditon": "",
            "webid": "",
            "outaddress": "",
            "shippertel": "",
            "modifyremark": "",
            "accleft": 0,
            "inroadcondition": "",
            "accsafe": 0,
            "accsend": 0,
            "addr": order_detail.get("addr"),
            "consigneecompany": "",
            "accmonth": 0,
            "accpackage": 0,
            "product": order_detail.get("product"),
            "outacc": 0,
            "outarriveddate": "",
            "esite": order_detail.get("esite"),
            "acctype": order_detail.get("acctype"),
            "outdate": order_detail.get("outdate"),
            "acchuikou": 0,
            "prescription": 0,
            "accyaokaozz": 0,
            "outcardno": "",
            "outremark": order_detail.get("outremark"),
            "vehiclearrived": "",
            "transneed": order_detail.get("transneed"),
            "__sortNum": 2,
            "__select": "selected"
        }
    ]
    return param


def get_express_name(express):
    if express is not None:
        express_name = express
        if "快递" in express:
            express_name = express.replace("快递", "")
        elif "速递" in express:
            express_name = express.replace("速递", "")
        return express_name
    return None


def get_sb_param(order_detail):
    arr = []
    p = {
        "ischecked": 1,
        "billdate": order_detail.get("billdate"),
        "bsite": order_detail.get("bsite"),
        "esite": order_detail.get("esite"),
        "middlesite": order_detail.get("middlesite"),
        "okprocess": order_detail.get("okprocess"),
        "hstate": 0,
        "state": 10,
        "unit": order_detail.get("unit"),
        "billno": order_detail.get("billno"),
        "shipper": order_detail.get("shipper"),
        "bdqitaremark": "",
        "consignee": order_detail.get("consignee"),
        "consigneetel": "",
        "consigneemb": order_detail.get("consigneemb"),
        "shippermb": order_detail.get("shippermb"),
        "shippertel": "",
        "vipno": "",
        "weight": 0,
        "volumn": 0,
        "qty": order_detail.get("qty"),
        "sheng": "",
        "city": "",
        "area": "",
        "town": "",
        "addr": order_detail.get("addr"),
        "acctrans": 0,
        "accsend": 0,
        "accbaoguan": 0,
        "accsf": 0,
        "remark": "",
        "content": f"{order_detail.get('product')}|{order_detail.get('qty')}",
        "khyydate": None,
        "product": order_detail.get("product"),
        "package": order_detail.get("package"),
        "genre": "",
        "outcygs": "1",
        "vehiclearrived": "1",
        "address": "",
        "dfyifan": 0,
        "accps": 0,
        "accsl": 0,
        "accaz": 0,
        "pdremark": "",
        "accfact": 0,
        "acctype": order_detail.get("acctype"),
        "accdaishou": 0,
        "accarrived": 0,
        "inonevehicleflag": None,
        "senddate": None,
        "s1": 0,
        "s2": 0,
        "s3": 0,
        "isbadsb": None,
        "hxno": "",
        "outtraceisover": "跟踪中",
        "tracedate": order_detail.get("outdate")
    }
    arr.append(p)
    return arr


def get_paisong_des(dbItem, logistics_des, mailNo):
    """
    获取派送描述内容，派送中的取件码是百分百存在的，要么用户传过来，要么自定义
    :param dbItem:
    :param logistics_des:
    :param mailNo:
    :return:
    """
    pickingCode: str = dbItem.get("pickingCode", None)
    pickingAddress: str = dbItem.get("pickingAddress", None)
    express = dbItem.get("express", None)
    if express is not None:
        if "快递" in express:
            express = express.replace("快递", "")
        if "速递" in express:
            express = express.replace("速递", "")
    if "单号后5位" in pickingCode:
        des = f"{pickingCode}，{logistics_des}"
    else:
        if pickingCode.startswith("取件请出示"):
            if not express:
                if not pickingAddress:
                    des = f"待取件，取件码:{pickingCode}，{logistics_des}"
                else:
                    des = f"待取件，取件码:{pickingCode}，取件地址：{pickingAddress}，{logistics_des}"
            else:
                if not pickingAddress:
                    des = f"待取件，【取件请报{express}单号后5位:{mailNo[-5:]}】，{logistics_des}"
                else:
                    des = f"待取件，【取件请报{express}单号后5位:{mailNo[-5:]}】，取件地址：{pickingAddress}，{logistics_des}"
        elif pickingCode.startswith("取件请报"):
            if not pickingAddress:
                des = f"待取件，{pickingCode}，{logistics_des}"
            else:
                des = f"待取件，{pickingCode}，取件地址：{pickingAddress}，{logistics_des}"
        else:
            if not pickingAddress:
                des = f"待取件，{express}取件码:{pickingCode}，{logistics_des}"
            else:
                des = f"待取件，{express}取件码:{pickingCode}，取件地址：{pickingAddress}，{logistics_des}"
    return des
